var express = require("express");
// var bodyParser = require("body-parser");

// 创建 application/x-www-form-urlencoded 编码解析
// var urlencodedParser = bodyParser.urlencoded({ extended: false })
const jwt = require('jsonwebtoken');  //用来生成token

var router = express.Router();

/* GET users listing. */
router.get("/", function(req, res, next) {
  res.send("respond with a resource");
});

router.post("/login", function(req, res) {
  console.log(req.body);
  var account = req.body.account;
  var password = req.body.password;

  // code 0 访问错误 返回 1访问成功 3登陆失效清除token
  var response = {
    code: "0",
    msg: "请输入正确手机号秘密",
  };

  if (!account) {
    res.end(JSON.stringify(response));
    return;
  }
  if (!password) {
    res.end(JSON.stringify(response));
    return;
  }

  // if(account){
  //   res.cookie("account", account, { maxAge: 60 * 1000, httpOnly: true });

  // }
  let secretOrPrivateKey = "bocai_privateKey";

  let token = jwt.sign(account, secretOrPrivateKey);

  // 输出 JSON 格式
  response = {
    code: "1",
    msg: "",
    data: {
      account: req.body.account,
      password: req.body.password,
      token:token,
    },
  };

  res.end(JSON.stringify(response));
});

// router.get('/login', function(req, res, next) {
//   console.log("---------"+req);
//   res.send("123");
// });

router.post("/loginOut", function(req, res) {
  // console.log("cookies"+req.cookies);
   // 输出 JSON 格式
   var response = {
    code: "1",
    msg: "",
    data: {
      msg:"退出登陆成功～"
    },
  };


  res.send(JSON.stringify(response));
});

// router.get('/adminLogin', function(req, res, next) {
//   res.send('adminLogin');
// });
module.exports = router;
